package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ${xinpl}
 * @Description 菜单接口服务实现类
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public PageResult findPage(QueryPageBean pageBean) throws Exception {
        PageHelper.startPage(pageBean.getCurrentPage(),pageBean.getPageSize());
        Page<Menu> page = menuDao.selectByCondition(pageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Menu menu) throws Exception {
        if(menu.getParentName() != null){
           int id =  menuDao.getMenuIdByparentName(menu.getParentName());
           menu.setParentMenuId(id);
        }
        menuDao.insertSelective(menu);
    }

    @Override
    public void delete(int id,int level) throws Exception {
        // 1.查询权限和角色是否存在关系
        int count1 = menuDao.findCountByPermissionIdAndRole(id);
        // 2.如果有关系则不允许删除
        if (count1 > 0) {
            throw new RuntimeException("id被外键引用,不能删除!");
        }
        // 3.自身表是否存在子项 level=1 才需要判断
        if(level == 1){
            int count2 = menuDao.findCountByPermissionId(id);
            // 4.如果有关系则不允许删除
            if (count2 > 0) {
                throw new RuntimeException("存在子项,不能删除!");
            }
        }
        // 5.无关系可以删除
        menuDao.deleteByPrimaryKey(id);
    }

    @Override
    public Menu findById(int id) throws Exception {
        return menuDao.selectByPrimaryKey(id);
    }

    @Override
    public void update(Menu menu) throws Exception {
        menuDao.updateByPrimaryKeySelective(menu);
    }

    @Override
    public Boolean checkMenuExist(String name) throws Exception {
        return null;
    }

    @Override
    public List<Menu> findParents() {
        return menuDao.findParents();
    }

    /**
     * 查找所有菜单
     * @return
     */
    @Override
    public List<Menu> findAllMenu() {
        return menuDao.findAllMenu();
    }


}
